// 应用数据模型和状态管理
window.AppData = {
    // 交易类定义
    Transaction: class {
        constructor(id, type, amount, categoryId, date, note) {
            this.id = id || this.generateId();
            this.type = type; // 'expense' 或 'income'
            this.amount = amount;
            this.categoryId = categoryId;
            this.date = date || new Date().toISOString();
            this.note = note || '';
        }
        
        generateId() {
            return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
        }
    },
    
    // 本地存储管理
    StorageManager: class {
        constructor() {
            this.storageKey = 'clearbookApp';
        }
        
        // 获取所有数据
        getData() {
            const data = localStorage.getItem(this.storageKey);
            return data ? JSON.parse(data) : {
                transactions: [],
                settings: {
                    savingsGoal: 10000
                }
            };
        }
        
        // 保存所有数据
        saveData(data) {
            localStorage.setItem(this.storageKey, JSON.stringify(data));
        }
        
        // 获取交易记录
        getTransactions() {
            return this.getData().transactions;
        }
        
        // 保存交易记录
        saveTransactions(transactions) {
            const data = this.getData();
            data.transactions = transactions;
            this.saveData(data);
        }
        
        // 获取设置
        getSettings() {
            return this.getData().settings;
        }
        
        // 保存设置
        saveSettings(settings) {
            const data = this.getData();
            data.settings = settings;
            this.saveData(data);
        }
    },
    
    // 交易管理
    TransactionManager: class {
        constructor() {
            this.storageManager = new window.AppData.StorageManager();
            
            // 初始化样例数据（如果没有数据）
            this.initializeIfEmpty();
        }
        
        // 获取所有交易
        getTransactions() {
            return this.storageManager.getTransactions();
        }
        
        // 添加交易
        addTransaction(transaction) {
            const transactions = this.getTransactions();
            transactions.push(transaction);
            this.storageManager.saveTransactions(transactions);
            return transaction;
        }
        
        // 更新交易
        updateTransaction(transaction) {
            const transactions = this.getTransactions();
            const index = transactions.findIndex(t => t.id === transaction.id);
            
            if (index !== -1) {
                transactions[index] = transaction;
                this.storageManager.saveTransactions(transactions);
                return true;
            }
            
            return false;
        }
        
        // 删除交易
        deleteTransaction(transactionId) {
            const transactions = this.getTransactions();
            const filteredTransactions = transactions.filter(t => t.id !== transactionId);
            
            if (filteredTransactions.length < transactions.length) {
                this.storageManager.saveTransactions(filteredTransactions);
                return true;
            }
            
            return false;
        }
        
        // 获取月度汇总
        getMonthlySummary(year, month) {
            const transactions = this.getTransactions();
            
            const monthlyTransactions = transactions.filter(transaction => {
                const date = new Date(transaction.date);
                return date.getFullYear() === year && date.getMonth() === month;
            });
            
            let totalExpense = 0;
            let totalIncome = 0;
            
            monthlyTransactions.forEach(transaction => {
                if (transaction.type === 'expense') {
                    totalExpense += transaction.amount;
                } else {
                    totalIncome += transaction.amount;
                }
            });
            
            return {
                totalExpense,
                totalIncome,
                balance: totalIncome - totalExpense
            };
        }
        
        // 过滤交易
        filterTransactions(filters) {
            let transactions = this.getTransactions();
            
            // 按类型过滤
            if (filters.type && filters.type !== 'all') {
                transactions = transactions.filter(t => t.type === filters.type);
            }
            
            // 按分类过滤
            if (filters.categories && filters.categories.length > 0) {
                transactions = transactions.filter(t => filters.categories.includes(t.categoryId));
            }
            
            // 按日期范围过滤
            if (filters.startDate && filters.endDate) {
                const start = new Date(filters.startDate);
                const end = new Date(filters.endDate);
                
                transactions = transactions.filter(t => {
                    const date = new Date(t.date);
                    return date >= start && date <= end;
                });
            }
            
            // 按金额范围过滤
            if (filters.minAmount) {
                transactions = transactions.filter(t => t.amount >= filters.minAmount);
            }
            
            if (filters.maxAmount) {
                transactions = transactions.filter(t => t.amount <= filters.maxAmount);
            }
            
            return transactions;
        }
        
        // 初始化样例数据
        initializeIfEmpty() {
            const transactions = this.getTransactions();
            
            if (transactions.length === 0) {
                // 生成当前月份的样例数据
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = currentDate.getMonth();
                
                // 样例交易
                const sampleTransactions = [
                    // 收入
                    new window.AppData.Transaction(
                        null,
                        'income',
                        8500,
                        'salary',
                        new Date(year, month, 5).toISOString(),
                        '5月工资'
                    ),
                    
                    // 支出
                    new window.AppData.Transaction(
                        null,
                        'expense',
                        56.5,
                        'food',
                        new Date(year, month, 8).toISOString(),
                        '午餐'
                    ),
                    new window.AppData.Transaction(
                        null,
                        'expense',
                        1200,
                        'housing',
                        new Date(year, month, 10).toISOString(),
                        '房租'
                    ),
                    new window.AppData.Transaction(
                        null,
                        'expense',
                        89.9,
                        'transport',
                        new Date(year, month, 12).toISOString(),
                        '加油'
                    ),
                    new window.AppData.Transaction(
                        null,
                        'expense',
                        320,
                        'shopping',
                        new Date(year, month, 15).toISOString(),
                        '衣服'
                    ),
                    new window.AppData.Transaction(
                        null,
                        'expense',
                        45.5,
                        'entertainment',
                        new Date(year, month, 18).toISOString(),
                        '电影票'
                    )
                ];
                
                this.storageManager.saveTransactions(sampleTransactions);
            }
        }
    },
    
    // 支出分类
    expenseCategories: [
        { id: 'food', name: '餐饮', icon: 'restaurant' },
        { id: 'shopping', name: '购物', icon: 'shopping_cart' },
        { id: 'transport', name: '交通', icon: 'directions_bus' },
        { id: 'housing', name: '住房', icon: 'home' },
        { id: 'entertainment', name: '娱乐', icon: 'sports_esports' },
        { id: 'medical', name: '医疗', icon: 'local_hospital' },
        { id: 'education', name: '教育', icon: 'school' },
        { id: 'other', name: '其他', icon: 'more_horiz' }
    ],
    
    // 收入分类
    incomeCategories: [
        { id: 'salary', name: '工资', icon: 'work' },
        { id: 'bonus', name: '奖金', icon: 'card_giftcard' },
        { id: 'investment', name: '投资', icon: 'savings' },
        { id: 'parttime', name: '兼职', icon: 'schedule' },
        { id: 'other_income', name: '其他', icon: 'more_horiz' }
    ],
    
    // 储蓄管理
    SavingsManager: class {
        constructor() {
            this.storageManager = new window.AppData.StorageManager();
        }
        
        // 获取所有储蓄目标
        getSavingsGoals() {
            const data = this.storageManager.getData();
            return data.savingsGoals || [];
        }
        
        // 保存所有储蓄目标
        saveSavingsGoals(savingsGoals) {
            const data = this.storageManager.getData();
            data.savingsGoals = savingsGoals;
            this.storageManager.saveData(data);
        }
        
        // 添加储蓄目标
        addSavingsGoal(savingsGoal) {
            const savingsGoals = this.getSavingsGoals();
            savingsGoal.id = Date.now().toString(36);
            savingsGoal.startDate = new Date().toISOString();
            savingsGoals.push(savingsGoal);
            this.saveSavingsGoals(savingsGoals);
            return savingsGoal;
        }
        
        // 更新储蓄目标
        updateSavingsGoal(savingsGoal) {
            const savingsGoals = this.getSavingsGoals();
            const index = savingsGoals.findIndex(g => g.id === savingsGoal.id);
            
            if (index !== -1) {
                savingsGoals[index] = savingsGoal;
                this.saveSavingsGoals(savingsGoals);
                return true;
            }
            
            return false;
        }
        
        // 删除储蓄目标
        deleteSavingsGoal(savingsGoalId) {
            const savingsGoals = this.getSavingsGoals();
            const filteredGoals = savingsGoals.filter(g => g.id !== savingsGoalId);
            
            if (filteredGoals.length < savingsGoals.length) {
                this.saveSavingsGoals(filteredGoals);
                return true;
            }
            
            return false;
        }
        
        // 获取当前储蓄进度
        getCurrentSavingsProgress() {
            const savingsGoals = this.getSavingsGoals();
            const transactionManager = new window.AppData.TransactionManager();
            const transactions = transactionManager.getTransactions();
            
            // 计算每个储蓄目标的进度
            return savingsGoals.map(goal => {
                // 获取创建日期之后的所有收入交易
                const startDate = new Date(goal.startDate);
                const relevantTransactions = transactions.filter(transaction => {
                    const date = new Date(transaction.date);
                    return date >= startDate && transaction.type === 'income';
                });
                
                // 计算总收入
                let totalIncome = 0;
                relevantTransactions.forEach(transaction => {
                    totalIncome += transaction.amount;
                });
                
                // 计算储蓄率 (假设用户想要储蓄总收入的一定比例)
                const savedAmount = totalIncome * (goal.savingRate / 100);
                const percentage = goal.targetAmount > 0 ? (savedAmount / goal.targetAmount) * 100 : 0;
                
                return {
                    ...goal,
                    savedAmount,
                    remaining: goal.targetAmount - savedAmount,
                    percentage: Math.min(percentage, 100)
                };
            });
        }
    },
    
    // 格式化工具
    formatCurrency(amount) {
        return amount.toFixed(2);
    },
    
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
        });
    }
}; 